<template>
  <ElDialog v-model="dialogVisible" :title="dialogTitle" width="38%" align-center>
    <ElForm ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <ElFormItem label="类型编码" prop="dict_type">
        <ElInput v-model="formData.dict_type" placeholder="请输入类型编码" disabled />
      </ElFormItem>
      <ElFormItem label="键" prop="dict_key">
        <ElInput v-model="formData.dict_key" placeholder="请输入键" />
      </ElFormItem>
      <ElFormItem label="值" prop="dict_value">
        <ElInput v-model="formData.dict_value" placeholder="请输入值" />
      </ElFormItem>
      <ElFormItem label="分类" prop="category">
        <ElInput v-model="formData.category" placeholder="请输入分类" />
      </ElFormItem>
      <ElFormItem label="选项" prop="options">
        <ElSelect v-model="formData.options" type="textarea" placeholder="请选择选项">
          <ElOption label="Y" value="Y" />
          <ElOption label="N" value="N" />
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="评分" prop="score">
        <ElInputNumber v-model="formData.score" :min="0" :max="100" :step="1" />
      </ElFormItem>
      <ElFormItem label="排序" prop="sort_order">
        <ElInputNumber v-model="formData.sort_order" :min="0" :step="1" />
      </ElFormItem>
    </ElForm>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" v-ripple>提交</el-button>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { createDictItem, updateDictItem, type DictItemResponse } from '@/api/system/dict_item'

interface Props {
  visible: boolean
  type: 'add' | 'edit'
  editData?: Partial<DictItemResponse>
  dictTypeCode?: string
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'submit'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

const dialogTitle = computed(() => (props.type === 'add' ? '添加字典项' : '编辑字典项'))

// 表单实例
const formRef = ref<FormInstance>()

// 表单数据
const formData = reactive({
  dict_type: '',
  dict_key: '',
  dict_value: '',
  category: '',
  score: undefined as number | undefined,
  options: '',
  sort_order: undefined as number | undefined
})

// 校验规则
const rules: FormRules = {
  dict_type: [{ required: true, message: '缺少类型编码', trigger: 'blur' }],
  dict_key: [{ required: true, message: '请输入键', trigger: 'blur' }],
  dict_value: [{ required: true, message: '请输入值', trigger: 'blur' }]
}

// 初始化表单
const initFormData = () => {
  const isEdit = props.type === 'edit' && props.editData
  const row = props.editData || {}
  Object.assign(formData, {
    dict_type: props.dictTypeCode || (isEdit ? (row.dict_type || '') : ''),
    dict_key: isEdit ? (row.dict_key || '') : '',
    dict_value: isEdit ? (row.dict_value || '') : '',
    category: isEdit ? (row.category || '') : '',
    score: isEdit ? (row.score as number | undefined) : undefined,
    options: isEdit ? (row.options || '') : '',
    sort_order: isEdit ? (row.sort_order as number | undefined) : undefined
  })
}

watch(
  () => [props.visible, props.type, props.editData, props.dictTypeCode],
  async ([visible]) => {
    if (visible) {
      initFormData()
      nextTick(() => formRef.value?.clearValidate())
    }
  },
  { immediate: true }
)

// 提交
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    const payload = {
      dict_type: formData.dict_type,
      dict_key: formData.dict_key,
      dict_value: formData.dict_value,
      category: formData.category || null,
      score: typeof formData.score === 'number' ? formData.score : undefined,
      options: formData.options || null,
      sort_order: typeof formData.sort_order === 'number' ? formData.sort_order : undefined
    }

    try {
      if (props.type === 'add') {
        await createDictItem({
          ...payload,
          options: payload.options ?? undefined
        })
      } else {
        const id = Number(props.editData?.id)
        if (!id) {
          ElMessage.error('缺少字典项ID，无法编辑')
          return
        }
        await updateDictItem(id, {
          ...payload,
          options: payload.options ?? undefined
        })
      }
      ElMessage.success('提交成功')
      emit('submit')
    } catch (error) {
      console.error('提交失败:', error)
      ElMessage.error('提交失败，请稍后重试')
    }
  })
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>